<template>
    <div class="layout-root  my-modal smalll-form focus-ico">
        <div style="width: 100%;margin-top: 5px;height: 400px;max-height: 400px;overflow-y: scroll;" class="calibratio_row" id="calibratio_row">
            <a-tree 
                :tree-data="treeData"
                checkable
                v-model:expandedKeys="tree_expandedKeys" 
                v-model:selectedKeys="tree_selectedKeys"
                v-model:checkedKeys="tree_checkedKeys"
                @check="tree_check"
                :autoExpandParent="true"
                :defaultExpandAll="true"
                v-if="treeData?.length>0"
                >
                <template #title="{ title, key, dataRef }">
                    <a-dropdown :trigger="['contextmenu']" style="color: #1890ff">
                        <span>
                            <template v-if="dataRef?.type === 'ctr'">
                                <span class="tree_title" :style="{color:$common_apis.Get_status_color_by_status(dataRef?.status)}">{{ title }}</span>
                                <a-badge status="processing" v-if="dataRef?.status==2" style="margin-left: 10px;"/>
                            </template>
                            <template v-else-if="dataRef?.type === 'tie'">
                                <span class="tree_title" :style="{color:$common_apis.Get_status_color_by_status(dataRef?.status)}">{{ title }}</span>
                                <a-badge status="processing" v-if="dataRef?.status==2"/>
                            </template>
                            <template v-else-if="dataRef?.type === 'multi'">
                                <span class="tree_title" :style="{color:$common_apis.Get_status_color_by_status(dataRef?.status)}">{{ title }}</span>
                                <a-badge status="processing" v-if="dataRef?.status==2"/>
                            </template>
                            <template v-else>{{ title }}</template>
                        </span>
                        <template #overlay >
                            <a-menu @click="({ key: menuKey }) => onContextMenuClick(menuKey, dataRef)" >
                                <template v-if="dataRef?.type == 'task' ">
                                    <a-menu-item key="run_match">匹配选定内容</a-menu-item>
                                    <a-menu-item key="calibration_update">更新定标索引</a-menu-item>
                                    <a-sub-menu key="calibration">
                                        <template #title><AppstoreOutlined />定标</template>
                                        <a-menu-item key="calibration_ccd_ctr_marking_run">CCD刺点刺点后外定标</a-menu-item>
                                        <a-menu-item key="calibration_ext_run">外定标</a-menu-item>
                                        <a-menu-item key="calibration_int_run">内定标</a-menu-item>
                                        <a-menu-item key="calibration_ext_int_run">外内迭代定标</a-menu-item>
                                        <a-menu-item key="calibration_run_rms">精度验证</a-menu-item>
                                        <!-- <a-menu-item key="calibration_show_rms">查看误差</a-menu-item> -->
                                    </a-sub-menu>
                                </template>
                                <!-- && $store.state.task?.prop?.ctl_Dom -->
                                <template v-if="dataRef?.fl_type == 'single' ">
                                    <a-menu-item key="XXX">CCD刺点</a-menu-item>
                                </template>
                                <template v-if="dataRef?.fl_type == 'multi'">
                                    <!-- <a-menu-item key="show_log">CCD刺点</a-menu-item> -->
                                </template>
                                <template v-if="dataRef?.type == 'ctr' || dataRef?.type == 'tie' || dataRef?.type == 'multi' ">
                                    <a-menu-item key="show_log">查看日志</a-menu-item>
                                    <a-menu-item key="show_xml">查看xml</a-menu-item>
                                    <a-menu-item key="tie_point_show" v-if="dataRef?.type == 'tie'">查看连接点</a-menu-item>
                                    <a-menu-item key="ctr_point_show" v-if="dataRef?.type == 'ctr'">查看控制点</a-menu-item>
                                    <a-menu-item key="ctr_point_marking" v-if="dataRef?.type == 'ctr'">CCD刺点</a-menu-item>
                                    <a-menu-item key="multi_point_show" v-if="dataRef?.type == 'multi'">查看多景点</a-menu-item>
                                </template>
                            </a-menu>
                        </template>
                    </a-dropdown>
                </template>
            </a-tree>
        </div>
        <div style="width: 100%;height: calc(100% -495px);max-height:calc(100% -495px);overflow-y: scroll;">
            <a-table 
            :data-source="Models" 
            :columns="Models_columns"
            class="task-table" 
            size="small" 
            :showHeader="true" 
            tableLayout="fixed"
            :pagination="false"
            bordered 
            rowKey="Mdl"
            style="overflow-y: scroll; max-height: 100%"
            >
            <template #bodyCell="{ text, record, index, column }">
                <template  v-if="column.dataIndex === 'ei'">
                    <a-input v-model:value="record.ei"/>
                </template>
                <template  v-if="column.dataIndex === 'ext'">
                    <span>{{record?.ext}}</span>
                </template>
                <template  v-if="column.dataIndex === 'ii'">
                    <a-input v-model:value="record.ii"/>
                </template>
                <template  v-if="column.dataIndex === 'int'">
                    <span>{{record?.int}}</span>
                </template>
            </template>
            </a-table>
        </div>
    </div>
    <show_log/>
    <match_points/>
    <ccd_cd_map/>
</template>
<script>
//任务运行状态status 1 没有运行 2运行中  3运行成功 4运行失败
import { defineAsyncComponent,h } from 'vue'
import { Modal,notification, Button } from 'ant-design-vue';
export default {
  data() {
    return {
        tree_expandedKeys:[],
        tree_selectedKeys: [],
        tree_checkedKeys: [],
        tree_checkedNodes: [],
        treeData:[], //左侧树的data
        
        Models:[],
        Models_columns: [
            {
                title: 'name',
                dataIndex: 'name',
                align: 'center',
                width: '350',
                ellipsis: true,
            },
            {
                title: 'dom',
                dataIndex: 'dom',
                align: 'center',
                width: '100',
                ellipsis: true,
            },
            {
                title: 'dem',   
                dataIndex: 'dem',
                align: 'center',
                width: '100',
                ellipsis: true,
            },
            
            {
                title: '外定标索引',
                dataIndex: 'ei',
                align: 'center',
                width: '100',
            },
            {
                title: '外定标文件',
                dataIndex: 'ext',
                align: 'center',
                width: '100',
                ellipsis: true,
            },
            {
                title: '内定标索引',
                dataIndex: 'ii',
                align: 'center',
                width: '100',
            },
            {
                title: '内定标文件',
                dataIndex: 'int',
                align: 'center',
                width: '100',
                ellipsis: true,
            },
        ],
        Models_pagination: {
            current: 1,
            size: 'small',
            pageSize: 10,
            total: 0,
            showTotal: (total, range) => {
                return `共 ${total},${range[0]}/${range[1]}`
            },
        },
        //
        mitt_web_exe_status_id:"",
        mitt_open_close_task_id:"",
        mitt_cidian_map_back_id:"",
    }
  },
  components: {
    show_log: defineAsyncComponent(() => import('@/components/common/show_log.vue')),
    match_points: defineAsyncComponent(() => import('@/components/task/match_points.vue')),
    ccd_cd_map: defineAsyncComponent(() => import('@/components/task/ccd_cd_map.vue')),
    // modal_select_server_dir: defineAsyncComponent(() => import('@/components/common/modal_select_server_dir.vue')),
    // sensor_cfg: defineAsyncComponent(() => import('@/components/task/sensor_cfg.vue')),
  },
  beforeUnmount() {
    this.$mitt.off('web_exe_status',this.mitt_web_exe_status_id);
    this.$mitt.off('open_close_task',this.mitt_open_close_task_id);
    this.$mitt.off('cidian_map_back',this.mitt_cidian_map_back_id);
  },
  mounted() {
    console.log("calibration.vue")
    //这行代码屏蔽浏览器默认菜单
    // document.getElementById('calibratio_row').oncontextmenu = function (e) {
    //     return false
    // }
    //从APP.vue传进来的任务状态参数
    this.mitt_web_exe_status_id=this.$mitt.on('web_exe_status', (uid,data) => {
      if(data?.key){
        let {key,status}=data
        this.set_node_name_status([key],status)
      }
    },this?.$?.uid);
    this.mitt_open_close_task_id=this.$mitt.on('open_close_task', (uid) => {
        if(this.$store.state.open_create==1){
            this.get_match_calibration()
        }
        else{
            this.Models=[]
            this.treeData=[]
        }
        console.log("emit open_close_task")
    },this?.$?.uid);
    this.mitt_cidian_map_back_id=this.$mitt.on('cidian_map_back', (data) => {
        this.update_ctr_point_marking(data)
    },this?.$?.uid);
    if(this.$store.state.open_create==1){
        this.get_match_calibration()
    }
  },
  methods: {
    async get_match_calibration(){
        let trans_tree = [
            {
                title: `项目名称-${this.$store.state.task?.task_name}`,
                key: '0-0',
                type:"task",
                children: [
                    {
                        title: `单TIF`,
                        key: '0-0-0',
                        children: [],
                        fl_type:"single",
                    },
                    {
                        title: '多景',
                        key: '0-0-1',
                        children: [],
                        fl_type:"multi",
                    },
                ],
            },
            
        ]
        let update_data={
            task_dir :this.$store.state.task_dir,
            task_name:this.$store.state.task.task_name,
        }
        this.$Loading.start();
        let _tree_data_result=await this.$apis.get_tree_data(update_data)
        console.log(_tree_data_result)
        let single_data=_tree_data_result?.single
        let multi_data=_tree_data_result?.multi
        let calibration_Model=_tree_data_result?.calibration
        //single_data to tree
        if(single_data?.length>=0){
            for (let j = 0; j < single_data?.length; j++) {
                let one_single_data = single_data[j];
                let one_children = {
                    title: one_single_data?.name,
                    key: `0-0-0-${j}`,
                    children:[]
                }
                if(one_single_data?.ctr?.length>0){
                    for (let k = 0; k < one_single_data?.ctr?.length; k++) {
                        let key=`0-0-0-${j}-${k}`
                        one_children.children.push(
                            {
                                title: `CCD 控制点 ${one_single_data?.ctr[k]}`,
                                name:one_single_data?.ctr[k],
                                key: key,
                                type:"ctr",
                                data:{
                                    ctr:one_single_data?.ctr[k],
                                    ctr_gcp:one_single_data?.ctr_gcp[k],
                                    ctr_match:one_single_data?.ctr_match[k],
                                    ctr_sim:one_single_data?.ctr_sim[k],
                                    mdl:one_single_data?.mdl,
                                }
                            }
                        )
                    }
                }
                if(one_single_data?.tie?.length>0){
                    for (let k = 0; k < one_single_data?.tie?.length; k++) {
                        let key=`0-0-0-${j}-${k+one_single_data?.ctr?.length}`
                        one_children.children.push({
                            title: `CCD 连接点 ${one_single_data?.tie[k]}`,
                            name:one_single_data?.tie[k],
                            key: key,
                            type:"tie",
                            data:{
                                tie:one_single_data?.tie[k],
                                tie_match:one_single_data?.tie_match[k],
                            }
                        })
                    }
                }
                trans_tree[0].children[0].children.push(one_children)
            }
        }
        // //multi_data to tree
        if(multi_data){
            trans_tree[0].children[1].children.push({
                title:  `多景连接 ${multi_data?.multi}`,
                name:multi_data?.multi,
                key: '0-0-1-0',
                type:"multi",
                data:multi_data
            })
        }
        if(calibration_Model?.length>=0){
            this.Models=calibration_Model
        }
        this.treeData = trans_tree
        console.log(this.treeData)
        let tree_node_keys=this.get_tree_node_key_from_tree(this.treeData[0])
        console.log(tree_node_keys)
        this.tree_checkedKeys=tree_node_keys?.keys
        this.tree_checkedNodes=tree_node_keys?.nodes
        this.$Loading.done();
    },
    async tree_check(checkedKeys, { checked, checkedNodes, node, event }) {
        console.log(checkedKeys, { checked, checkedNodes, node, event })
        // console.log(this.tree_checkedKeys)
        this.tree_checkedNodes=checkedNodes
    },
    //tree树的一些事件 操作dblclic 主要用于fit操作
    tree_dblclick(event, dataRef){
        // if(dataRef.checked){
        //     this.onContextMenuClick("fit",dataRef);
        // }
    },
    //设置运行的任务状态
    set_node_name_status(xml_keys,status){
        for (let i = 0; i < xml_keys?.length; i++) {
            let one_key=xml_keys[i]
            let one_key_split=one_key?.split("-")
            one_key_split.splice(0,1)
            if(one_key_split?.length==4){
                this.treeData[one_key_split[0]].children[one_key_split[1]].children[one_key_split[2]].children[one_key_split[3]].status=status
            }
            else if(one_key_split?.length==3){
                this.treeData[one_key_split[0]].children[one_key_split[1]].children[one_key_split[2]].status=status
            }
        }
    },
    get_tree_node_key_from_tree(_tree_data){
        let tree_checkedNodes=[]
        let tree_checkedNodeKeys=[]
        tree_checkedNodes.push(_tree_data)
        tree_checkedNodeKeys.push(_tree_data?.key)
        if(_tree_data?.children?.length>0){
            for (let k = 0; k < _tree_data?.children?.length; k++) {
                let one_tree_data=_tree_data?.children[k]
                let one_tree_datas=this.get_tree_node_key_from_tree(one_tree_data)
                tree_checkedNodes=tree_checkedNodes.concat(one_tree_datas?.nodes)
                tree_checkedNodeKeys=tree_checkedNodeKeys.concat(one_tree_datas?.keys)
            }
        }
        return {
            nodes:tree_checkedNodes,
            keys:tree_checkedNodeKeys
        }
    },
    get_xml_dataRefs_to_array(xml_dataRefs){
        let single_dataRefs =xml_dataRefs.filter((val)=>{
            return val?.type == "ctr" || val?.type == "tie" 
        })
        let multi_dataRefs =xml_dataRefs.filter((val)=>{
            return val?.type == "multi" 
        })
        single_dataRefs.sort((a,b)=>{
            return a?.key-b?.key
        })
        let xmls=[]
        for (let k = 0; k < single_dataRefs?.length; k++) {
            xmls.push({
                type:single_dataRefs[k]?.type,
                xml:single_dataRefs[k]?.name,
                key:single_dataRefs[k]?.key,
            })
        }
        for (let k = 0; k < multi_dataRefs?.length; k++) {
            xmls.push({
                type:multi_dataRefs[k]?.type,
                xml:multi_dataRefs[k]?.name,
                key:multi_dataRefs[k]?.key,
            })
        }
        return xmls
    },
    get_xml_dataRefs_keys(xml_dataRefs){
        let keys=[]
        for (let k = 0; k < xml_dataRefs?.length; k++) {
            keys.push(xml_dataRefs[k]?.key)
        }
        return keys
    },
    async update_calibration(){
        this.$Loading.start();
        let update_data={
            task_dir :this.$store.state.task_dir,
            task_name:this.$store.state.task.task_name,
            models:JSON.stringify(this.Models)
        }
        let update_data_result=await this.$apis.update_calibration(update_data)
        if(update_data_result){
            this.$message.success("更新定标文件成功")
        }
        else{
            this.$message.error("更新定标文件失败")
        }
        this.$Loading.done();  
    },
    //匹配选定内容
    async run_match(){
        let xml_dataRefs = this.tree_checkedNodes.filter((val)=>{
            return val?.type == "ctr" || val?.type == "tie" || val?.type == "multi"
        })
        if(xml_dataRefs?.length>0){
            let xmls=this.get_xml_dataRefs_to_array(xml_dataRefs)
            let xml_keys=this.get_xml_dataRefs_keys(xml_dataRefs)
            this.set_node_name_status(xml_keys,1)
            let update_data={
                task_dir :this.$store.state.task_dir,
                task_name:this.$store.state.task_name,
                xml:JSON.stringify(xmls)
            }
            this.$Loading.start();
            let update_data_result=await this.$apis.run_match(update_data)
            let result=update_data_result?.result
            this.$Loading.done();
            if(result){
                this.$message.success("匹配成功")
            }
            else{
                this.$message.error("匹配失败")
            }
        }
        else{
            this.$message.info("没有选择项")
        }
        
        return ;
    },
    //外定标
    async run_ext_calibration(){
        this.$Loading.start();
        let update_data={
            task_dir :this.$store.state.task_dir,
            task_name:this.$store.state.task.task_name,
        }
        let update_data_result=await this.$apis.run_ext_calibration(update_data)
        let result=update_data_result?.result
        if(result){
            this.$message.success("外定标成功")
        }
        else{
            this.$message.error("外定标失败")
        }
        this.$Loading.done();  
    },
    //内定标
    async run_int_calibration(){
        this.$Loading.start();
        let update_data={
            task_dir :this.$store.state.task_dir,
            task_name:this.$store.state.task.task_name,
        }
        let update_data_result=await this.$apis.run_int_calibration(update_data)
        let result=update_data_result?.result
        if(result){
            this.$message.success("内定标成功")
        }
        else{
            this.$message.error("内定标失败")
        }
        this.$Loading.done();  
    },
    //外内迭代定标
    async run_ext_int_calibration(){
        this.$Loading.start();
        let update_data={
            task_dir :this.$store.state.task_dir,
            task_name:this.$store.state.task.task_name,
        }
        let update_data_result=await this.$apis.run_ext_int_calibration(update_data)
        let result=update_data_result?.result
        if(result){
            this.$message.success("外内迭代定标成功")
        }
        else{
            this.$message.error("外内迭代定标失败")
        }
        this.$Loading.done();
    },
    //精度验证
    async run_rms(){
        this.$Loading.start();
        let update_data={
            task_dir :this.$store.state.task_dir,
            task_name:this.$store.state.task.task_name,
        }
        let update_data_result=await this.$apis.run_rms(update_data)
        let result=update_data_result?.result
        if(result){
            this.$message.success("精度验证成功")
        }
        else{
            this.$message.error("精度验证失败")
        }
        this.$Loading.done();
    },
    open_notification(description,cb){
        const key = `open${Date.now()}`;
        notification.open({
            message: '提示:',
            description:description,
            btn: () =>
                h(Button,{
                    type: 'primary',
                    size: 'small',
                    onClick: () =>{
                            notification.close(key)
                            if(typeof cb==="function"){
                                cb()
                            }
                        }
                    },
                    { default: () => '继续' },
                )
            ,
            key,
            duration:null
        });
    },
    async onContextMenuClick(menuKey, dataRef) {
        console.log(dataRef)
        if (menuKey == "run_match") {
            this.run_match()
        }
        //更新定标文件
        else if(menuKey == "calibration_update"){
            this.update_calibration()
        }
        //CCD刺点刺点后外定标
        else if(menuKey == "calibration_ccd_ctr_marking_run"){
            this.$Loading.start();
            let update_data={
                task_dir :this.$store.state.task_dir,
                task_name:this.$store.state.task.task_name,
            }
            let update_data_result=await this.$apis.update_calibration_NumberofAngles(update_data)
            let result=update_data_result?.result
            if(result){
                this.$message.success("精度验证成功")
            }
            else{
                this.$message.error("精度验证失败")
            }
            this.$Loading.done();
        }
        //外定标
        else if(menuKey == "calibration_ext_run"){
            this.run_ext_calibration()
        }
        //内定标
        else if(menuKey == "calibration_int_run"){
            this.run_int_calibration()
        }
        //外内迭代定标
        else if(menuKey == "calibration_ext_int_run"){
            this.run_ext_int_calibration()
        }
        //精度验证
        else if(menuKey == "calibration_run_rms"){
            this.run_rms()
        }
        //查看精度
        else if(menuKey == "calibration_show_rms"){

        }
        //  next //
        else if (menuKey == "show_log") {
            let log_result = await this.$apis.get_log({
                xml: dataRef?.name,
            })
            if (log_result) {
                let lines= log_result.split("\r\n")
                if(lines?.length==1){
                    lines= log_result.split("\n")
                }
                let new_lines=[]
                for (let i = 0; i < lines.length; i++) {
                    if(lines[i]){
                        new_lines.push(lines[i])
                    }
                }
                this.$mitt.iemit('show_log_modal', new_lines,this?.$?.uid);
            }
            else {
                this.$message.success(`获取日志失败`)
            }
        }
        else if (menuKey == "show_xml") {
            window.open(`${window.server_url}ser/get_xml?xml=${dataRef?.name}`, '_blank')
        }
        else if (menuKey == "tie_point_show") {
            this.$mitt.iemit("match_point",{xml:dataRef?.name,type:"tie"},this?.$?.uid)
        }
        else if (menuKey == "ctr_point_show") {
            this.$mitt.iemit("match_point",{xml:dataRef?.name,type:"ctr"},this?.$?.uid)
        }
        else if (menuKey == "ctr_point_marking") {
            this.open_notification("在原始影像和仿真影像上粗略刺点(只需一个)...",()=>{
                this.$mitt.iemit("cidian_map",{xml:dataRef?.name,type:"ctr"},this?.$?.uid)
            })
            // this.$mitt.iemit("match_point",{xml:dataRef?.name,type:"tie"},this?.$?.uid)
        }
        else if (menuKey == "multi_point_show") {
            this.$mitt.iemit("match_point",{xml:dataRef?.name,type:"multi"},this?.$?.uid)
        }
    },
    async update_ctr_point_marking(data){
        console.log("update_ctr_point_marking",data)
        let { xml_object,points}=data
        if(points?.length>0){
            this.$Loading.start();
            let update_data={
                task_dir :this.$store.state.task_dir,
                task_name:this.$store.state.task.task_name,
                xml:xml_object?.xml,
                type:xml_object?.type,
                points:JSON.stringify(points),
            }
            let update_data_result=await this.$apis.update_match_point(update_data)
            if(update_data_result){
                this.$message.success("更新CCD CTR 刺点文件成功")
            }
            else{
                this.$message.error("更新CCD CTR 刺点文件失败")
            }
            this.$Loading.done();
        }
    },

    
  },
}
</script>
<style>
.calibratio_row .ant-tree{
    width: 100%;
    font-size: 10px;
}
.calibratio_row .ant-tree .ant-tree-title{
    font-size: 10px;
}
.tree_title{
    padding-right: 20px;
}
</style>